package com.codingfuture.erp_system.web.controller;

import com.codingfuture.erp_system.dto.PageData;
import com.codingfuture.erp_system.entity.Role;
import com.codingfuture.erp_system.service.RoleManageService;
import com.codingfuture.erp_system.util.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("/v2")
@RestController
public class RoleManageController {

    @Autowired
    private RoleManageService roleManageService;

    //数据渲染
    @GetMapping("/role/listByPage")
    public Result findByAll(@RequestParam(defaultValue = "1") int page,
                            @RequestParam(defaultValue = "10") int rows,
                            String name) {
        Page<Object> page1 = PageHelper.startPage(page, rows);
        List<Role> list = roleManageService.findByAll(name);
        PageData<Role> data = new PageData<>(list, page1.getTotal());
        return Result.ok(data);
    }

    //新增
    @PostMapping("/role/add")
    public Result insert(String name) {
        Boolean result = roleManageService.insert(name);
        return result ? Result.ok() : Result.error(201, "错误");
    }

    //id回显
    @GetMapping("/role/selectone")
    public Result findById(int id, HttpSession session) {
        session.setAttribute("roleId", id);
        Role role = roleManageService.findById(id);
        return Result.OK(role);
    }

    //编辑
    @PostMapping("/role/update")
    public Result update(String name, HttpSession session) {
        Object id = session.getAttribute("roleId");
        Boolean result = roleManageService.update(name, (Integer) id);
        return result ? Result.ok() : Result.error(201, "错误");
    }

    //删除
    @DeleteMapping("/role")
    public Result delete(int id) {
        Boolean result = roleManageService.delete(id);
        return result ? Result.ok() : Result.error(201, "错误");
    }

}
